<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="https://jsonplaceholder.typicode.com/posts/"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="handleAvatarSuccess"
    >
      <img v-if="value" :src="value" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <i v-if="value" class="errorIcon el-icon-error" @click="clearImg" />
  </div>
</template>
<script>
// 导包
import COS from 'cos-js-sdk-v5'
// 实例化
const cos = new COS({
  SecretId: 'AKIDJPGrCG2XmkRqzrTntiHZaKnzuYv1qPhh', // 身份识别 ID
  SecretKey: 'kDPKyLRHm47uRipgIekaBWbQ0KODn8D2' // 身份密钥
})

export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  methods: {
    clearImg() {
      this.value = ''
    },
    // 自定义导入图片方法
    handleAvatarSuccess(params) {
      // 在需求的时候调用方法即可
      cos.putObject(
        {
          Bucket: 'sun0310-1306581532' /* 容器名 必须 */,
          Region: 'ap-shenzhen-fsi' /* 存储桶所在地域，必须 */,
          Key: params.file.name /* 文件标记,可以用名字代替 必须 */,
          StorageClass: 'STANDARD' /* 固定值可以不管他 必须 */,
          Body: params.file, // 上传文件对象
          onProgress: progressData => {
            // 上传进度
            console.log(JSON.stringify(progressData))
          }
        },
        (err, data) => {
          // 有错就是err 没错就是 data
          if (data.statusCode === 200) {
            // this.imageUrl = `http://${data.Location}`
            this.$emit('input', `http://${data.Location}`)
          }
        }
      )
    },
    beforeAvatarUpload(file) {
      //  配置上传图片支持的格式
      const isJPG = ['image/jpeg', 'image/png', 'image/jif'].includes(file.type)
      // 配置上传图片的大小
      const isLt50M = file.size / 1024 / 1024 < 50

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt50M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt50M
    }
  }
}
</script>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  //   overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
i.errorIcon {
  font-size: 20px;
  position: absolute;
  background-color: white;
  border-radius: 50px;
  top: -10px;
  left: 168px;
  color: red;
}
</style>
